﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Web;
using ImageResizer;
using log4net;
using System.Drawing;

namespace Cnm.Core.Ultities
{
    public static class ImageHelper
    {
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        const string Append = "tayninhinfo_";
        private const string OriginalFolder = "_originals/";
        private const string NormalFolder = "_normals/";
        private const string ThumbFolder = "_thumbs";

        public static string RenameImageUploadFile(HttpPostedFileBase file, string folder, int widthNorms, int widthThumbs, Int32 counter = 0)
        {
            try
            {
                var fileName =CommonHelpers.Title2Alias(Path.GetFileNameWithoutExtension(file.FileName)) + Path.GetExtension(file.FileName);

                string finalFileName = Append + ((counter).ToString(CultureInfo.InvariantCulture)) + "_" + fileName;
                if (File.Exists(HttpContext.Current.Request.MapPath(folder + NormalFolder + finalFileName)))
                {
                    //file exists 
                    return RenameImageUploadFile(file, folder, widthNorms, widthThumbs, ++counter);
                }
                //file doesn't exist, upload item but validate first
                return UploadImageFile(file, folder, widthNorms, widthThumbs, finalFileName);
            }catch
            {
                return null;
            }
        }

        private static string UploadImageFile(HttpPostedFileBase file, string folder, int widthNorms, int widthThumbs, string fileName)
        {
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
            var pathOrgin = Path.Combine(HttpContext.Current.Request.MapPath(folder + OriginalFolder), fileName);
            var pathNorm = Path.Combine(HttpContext.Current.Request.MapPath(folder + NormalFolder), fileNameWithoutExtension);
            var pathThumb = Path.Combine(HttpContext.Current.Request.MapPath(folder + ThumbFolder), fileNameWithoutExtension);
            var extension = Path.GetExtension(file.FileName);
            
            //make sure the file is valid
            if (!FileHelper.ValidateExtension(extension))
            {
                return string.Empty;
            }

            try
            {
                file.SaveAs(pathOrgin);

                var versions = new Dictionary<string, string>
                {
                    {pathNorm, "width=" + widthNorms + "&format=jpg"},
                    {pathThumb, "width=" + widthThumbs + "&format=jpg"}
                };
                
                foreach (string suffix in versions.Keys)
                {
                    //Let the image builder add the correct extension based on the output file type
                    fileName = ImageBuilder.Current.Build(file, suffix, new ResizeSettings(versions[suffix]), false, true);
                }
                return Path.GetFileName(fileName);
            }
            catch (Exception ex)
            {
                Logger.Error(MethodBase.GetCurrentMethod().Name, ex);
                return string.Empty;
            }
        }

        //public static Image ScaleBySize(Image imgPhoto, int size)
        //{
        //    if (size == 0)
        //        return imgPhoto;

        //    int logoSize = size;

        //    float sourceWidth = imgPhoto.Width;
        //    float sourceHeight = imgPhoto.Height;
        //    float destHeight = 0;
        //    float destWidth = 0;
        //    const int sourceX = 0;
        //    const int sourceY = 0;
        //    const int destX = 0;
        //    const int destY = 0;

        //    //// Resize Image to have the height = logoSize/2 or width = logoSize.
        //    //// Height is greater than width, set Height = logoSize and resize width accordingly
        //    //if (sourceWidth > (2 * sourceHeight))
        //    //{
        //    //    destWidth = logoSize;
        //    //    destHeight = (float)(sourceHeight * logoSize / sourceWidth);
        //    //}
        //    //else
        //    //{
        //    //    int h = logoSize / 2;
        //    //    destHeight = h;
        //    //    destWidth = (float)(sourceWidth * h / sourceHeight);
        //    //}
        //    // Width is greater than height, set Width = logoSize and resize height accordingly
        //    float scale = 1;
        //    if (sourceWidth < sourceHeight)
        //    {
        //        if (Math.Abs(sourceWidth - 0) > 0)
        //            scale = logoSize / sourceWidth;
        //    }
        //    else
        //    {
        //        if (Math.Abs(sourceHeight - 0) > 0)
        //            scale = logoSize / sourceHeight;
        //    }
        //    //if(Math.Abs(sourceWidth - 0) > 0)
        //    // scale = logoSize/sourceWidth;
        //    destWidth = scale*sourceWidth;
        //    destHeight = scale*sourceHeight;

        //    var bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
        //                                PixelFormat.Format32bppPArgb);
        //    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        //    Graphics grPhoto = Graphics.FromImage(bmPhoto);
        //    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        //    grPhoto.DrawImage(imgPhoto,
        //        new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
        //        new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
        //        GraphicsUnit.Pixel);

        //    grPhoto.Dispose();
        //    //bmPhoto.Dispose();

        //    return bmPhoto;
        //}

        public static bool DeleteImageUploadByName(string name, string folder)
        {
            try
            {
                if (File.Exists(HttpContext.Current.Request.MapPath(folder + "_normals/" + name)))
                {
                    File.Delete(HttpContext.Current.Request.MapPath(folder + "_normals/" + name));
                }

                if (File.Exists(HttpContext.Current.Request.MapPath(folder + "_thumbs/" + name)))
                {
                    File.Delete(HttpContext.Current.Request.MapPath(folder + "_thumbs/" + name));
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string CreateImageName(string pathDir)
        {
            try
            {
                List<string> lstFileName = FileHelper.GetAllFileNameFromDir(pathDir);

                var rand = new Random();
                int id = rand.Next(100000000, Int32.MaxValue);

                while (lstFileName.IndexOf(id.ToString(CultureInfo.InvariantCulture)) != -1)
                {
                    id = rand.Next(100000000, Int32.MaxValue);
                }

                return id.ToString(CultureInfo.InvariantCulture);
            }
            catch
            {
                return null;
            }
        }

        public static bool FileExist(string folder, string fileName, string typeFolder = "thumbs")
        {
            if(typeFolder == "thumbs")
                return File.Exists(HttpContext.Current.Request.MapPath(folder + "_thumbs/" + fileName));
            if(typeFolder == "norms")
                return File.Exists(HttpContext.Current.Request.MapPath(folder + "_normals/" + fileName));

            return File.Exists(HttpContext.Current.Request.MapPath(folder + "_thumbs/" + fileName));
        }

        // Phương thức cũ
        //public Image ScaleBySize(Image imgPhoto, int size)
        //{
        //    int logoSize = size;

        //    float sourceWidth = imgPhoto.Width;
        //    float sourceHeight = imgPhoto.Height;
        //    float destHeight = 0;
        //    float destWidth = 0;
        //    int sourceX = 0;
        //    int sourceY = 0;
        //    int destX = 0;
        //    int destY = 0;

        //    // Resize Image to have the height = logoSize/2 or width = logoSize.
        //    // Height is greater than width, set Height = logoSize and resize width accordingly
        //    if (sourceWidth > (2 * sourceHeight))
        //    {
        //        destWidth = logoSize;
        //        destHeight = (float)(sourceHeight * logoSize / sourceWidth);
        //    }
        //    else
        //    {
        //        int h = logoSize / 2;
        //        destHeight = h;
        //        destWidth = (float)(sourceWidth * h / sourceHeight);
        //    }
        //    // Width is greater than height, set Width = logoSize and resize height accordingly

        //    Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
        //                                PixelFormat.Format32bppPArgb);
        //    bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        //    Graphics grPhoto = Graphics.FromImage(bmPhoto);
        //    grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

        //    grPhoto.DrawImage(imgPhoto,
        //        new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
        //        new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
        //        GraphicsUnit.Pixel);

        //    grPhoto.Dispose();

        //    return bmPhoto;
        //}
    }
}